<template>
  <div class="assignment-area">
    <!-- 作业栏标题 -->
    <h2 class="title">作业栏</h2>

    <!-- 作业表格 -->
    <div class="assignment-table">
      <el-table :data="tableData" stripe>
        <el-table-column label="作业Id" prop="id" />
        <el-table-column label="作业名称" prop="name" />
        <el-table-column label="截止日期" prop="deadline" />
        <el-table-column label="文件">
          <template slot-scope="scope">
            <span>{{ scope.row.file }}</span>
            <button class="download-btn" @click="handleDownload(scope.row.id)">下载</button>
          </template>
        </el-table-column>

        <!-- 新增上传作业栏 -->
        <el-table-column label="上传作业">
          <template slot-scope="scope">
            <input 
              type="file" 
              :id="`fileInput_${scope.row.id}`" 
              @change="handleFileChange($event, scope.row.id)" 
              style="display: none" 
            />
            <button class="select-file-btn" @click="handleSelectFile(scope.row.id)">选择文件</button>
            <button class="upload-btn" @click="handleUpload(scope.row.id)">上传作业</button>
          </template>
        </el-table-column>

        <!-- 显示互评状态 -->
        <el-table-column label="互评状态">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.isMutual" type="success">已设置互评</el-tag>
              <el-tag v-else type="info">未设置互评</el-tag>
            </div>
            <div v-if="scope.row.isMutual">
              <button class="review-btn" @click="navigateToReview(scope.row.id)">进入互评</button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分数" prop="score" /> 
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, getCurrentInstance } from 'vue';
import axios from 'axios';

export default {
  setup() {
    // 获取当前组件实例
    const instance = getCurrentInstance();
    
    // 使用 this.$route 和 this.$router 获取路由信息
    const route = instance.proxy.$route;
    const router = instance.proxy.$router;
    
    // 获取 courseId
    const courseId = route.params.courseId;

    // 定义响应式数据
    const tableData = ref([]); // 存储表格数据
    const selectedFiles = ref({}); // 存储选择的文件

    // 页面加载时获取作业数据
    const fetchHomeworkData = async (courseId) => {
      try {
        const response = await axios.get("/homework/viewhomeworkitem", {
          params: { courseId },
        });

        // 初始化数据
        tableData.value = response.data.map((item) => ({
          id: item.homeworkId,
          name: item.title,
          deadline: item.deadLine,
          file: item.fileName,
          isMutual: item.isMutual === "true", // 确保为布尔值
          score: 0,
        }));

        tableData.value.forEach((element) => {
          axios
            .get("/homework/studentviewscore", {
              params: {
                homeworkId: element.id,
                userId: instance.proxy.$store.state.status.userId,
              },
            })
            .then((resp) => {
              element.score = resp.data;
              console.log(tableData.value);
            });
        });
      } catch (error) {
        console.error("获取作业数据失败:", error);
      }
    };

    // 下载作业
    const handleDownload = async (homeworkId) => {
      try {
        const response = await axios.get("/homework/downloadhomeworkitem", {
          params: { homeworkId },
          responseType: "blob", // 确保接收到的是文件
        });

        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", `homework_${homeworkId}.pdf`); // 根据实际文件格式设置扩展名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error("下载作业失败:", error);
      }
    };

    // 选择文件
    const handleSelectFile = (homeworkId) => {
      const input = document.querySelector(`#fileInput_${homeworkId}`);
      if (input) {
        input.click(); // 触发文件输入框的点击事件
      }
    };

    // 处理文件选择
    const handleFileChange = (event, homeworkId) => {
      selectedFiles.value[homeworkId] = event.target.files[0]; // 存储选择的文件
    };

    // 上传作业
    const handleUpload = async (homeworkId) => {
      const file = selectedFiles.value[homeworkId];
      if (!file) {
        alert("请先选择文件！");
        return;
      }

      const formData = new FormData();
      formData.append("file", file); // 将文件附加到 FormData
      formData.append("homeworkId", homeworkId); // 传递作业ID
      formData.append("userId", instance.proxy.$store.state.status.userId);

      try {
        const response = await axios.post("/homework/submithomework", formData, {
          headers: { "Content-Type": "multipart/form-data" },
        });
        console.log("上传成功:", response.data);
      } catch (error) {
        console.error("上传作业失败:", error);
      }
    };

    // 跳转到互评界面
    const navigateToReview = (homeworkId) => {
      const userId = this.$store.state.status.userId;
      router.push({ name: "MutualEvaluation", params: { homeworkId ,userId } });
    };

    // 页面加载时调用获取作业数据
    onMounted(() => {
      console.log("cid: ", courseId);
      fetchHomeworkData(courseId);
    });

    return {
      courseId,
      tableData,
      selectedFiles,
      handleDownload,
      handleSelectFile,
      handleFileChange,
      handleUpload,
      navigateToReview,
    };
  },
};
</script>

<style scoped>
.assignment-area {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

.title {
  font-size: 50px;
  font-weight: bold;
  margin-bottom: 20px;
}

.assignment-table {
  width: 100%;
  border-collapse: collapse;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.download-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
  margin-left: 5px;
}

.download-btn:hover {
  background-color: darkred;
}

.select-file-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
  margin-right: 5px;
}

.select-file-btn:hover {
  background-color: #0b7dda;
}

.upload-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.upload-btn:hover {
  background-color: #45a049;
}

.review-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.review-btn:hover {
  background-color: #e68a00;
}
</style>
